package com.nullyb.springbootshardingjdbc.algorithm;

import com.alibaba.fastjson.JSON;
import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;

/**
 * 分表算法
 */
@Slf4j
public class TableShardingAlgorithm implements PreciseShardingAlgorithm<String> {
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<String> preciseShardingValue) {
        log.info("collection:" + JSON.toJSONString(collection)+",PreciseShardingValue:" + JSON.toJSONString(preciseShardingValue));
        for (String table:collection) {
            String shardingVale = preciseShardingValue.getValue().substring(0,6);
            boolean equals = table.substring(table.indexOf("_")+1).equals(shardingVale);
            if (equals){
                log.info("tableName:" + table);
                return table;
            }
        }
        throw new RuntimeException("路由表失败！");
    }
}
